<template>
  <div class="customer-page">
    <!-- 🔍 搜索区 -->
    <div class="top-row">
      <el-input
        v-model="searchQuery"
        placeholder="请输入客户姓名或电话"
        clearable
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 📋 客户表格容器 -->
    <div class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="paginatedData"
        style="width: 100%"
        border
        v-if="paginatedData.length > 0"
      >
        <!-- 序号列 -->
        <el-table-column label="序号" width="60">
          <template #default="{ $index }">
            {{ (currentPage - 1) * pageSize + $index + 1 }}
          </template>
        </el-table-column>

        <!-- 其他字段 -->
        <el-table-column prop="customerId" label="ID" />
        <el-table-column prop="customerName" label="姓名" />
        <el-table-column prop="phoneNumber" label="手机号" />
        <el-table-column prop="platformBalance" label="余额" />
        <el-table-column prop="points" label="积分" />

        <!-- 操作列 -->
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="showRecharge(row)">充值</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 没有数据时提示 -->
      <div v-else class="no-data">暂无数据</div>
    </div>

    <!-- 📑 分页（在表格外部，不受背景影响） -->
    <el-pagination
      v-if="filteredData.length > 0"
      background
      layout="prev, pager, next"
      :total="filteredData.length"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      class="pagination"
    />

    <!-- 💰 充值弹窗 -->
    <el-dialog title="充值" v-model="rechargeDialogVisible" width="420px">
      <div class="recharge-content">
        <el-form :model="rechargeForm" label-width="80px">
          <el-form-item label="客户姓名">
            <el-input v-model="rechargeForm.customerName" disabled />
          </el-form-item>

          <!-- ✅ 充值金额 -->
          <el-form-item label="充值金额">
            <el-input v-model.number="rechargeForm.amount" type="number" placeholder="充值余额" />
          </el-form-item>

          <!-- ✅ 新增：充值积分 -->
          <!-- <el-form-item label="充值积分">
            <el-input v-model.number="rechargeForm.points" type="number" placeholder="充值积分" />
          </el-form-item> -->
        </el-form>
      </div>

      <template #footer>
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRecharge">确认充值</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { getCustomerL, chongZhi } from '@/api/customer'
import type { CustomerT } from '@/api/customer'
import { ElMessageBox, ElMessage } from 'element-plus'

export default defineComponent({
  setup() {
    const searchQuery = ref('')
    const allData = ref<CustomerT[]>([])
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = 10

    const detailDialogVisible = ref(false)
    const rechargeDialogVisible = ref(false)
    const currentCustomer = ref<CustomerT | null>(null)
    const rechargeForm = ref({ customerId: 0, amount: 0, customerName: '' })

    const filteredData = computed(() => allData.value)
    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize
      return filteredData.value.slice(start, start + pageSize)
    })

    const loadData = async () => {
      loading.value = true
      allData.value = await getCustomerL()
      loading.value = false
    }

    const handleSearch = () => {
      currentPage.value = 1
      loadData()
    }

    const showRecharge = (row: CustomerT) => {
      rechargeForm.value.customerName = row.customerName
      rechargeForm.value.customerId = row.customerId
      rechargeForm.value.amount = 0
      currentCustomer.value = row
      rechargeDialogVisible.value = true
    }

    async function confirmRecharge() {
      const { amount, customerName,customerId } = rechargeForm.value
      if (!amount || amount <= 0) {
        ElMessage.warning('请输入大于 0 的金额')
        return
      }

      try {
        await ElMessageBox.confirm(`确定为客户「${customerName}」充值 ${amount} 元？`, '提示')
        const res = await chongZhi({ customerId, amount })
        console.log(11,res)
        if (res) {
          // ① 本地实时更新余额 & 积分（可选）
          if (currentCustomer.value) {
            currentCustomer.value.memberBalance += amount
            if (res.data) currentCustomer.value.points = res.data.points
          }
          // ② 刷新整表（简单）或只更新行（上面已做）
          await loadData()
          ElMessage.success('充值成功')
          rechargeDialogVisible.value = false
        } else {
          ElMessage.error(res.msg || '充值失败')
        }
      } catch {
        /* 用户取消 */
      }
    }

    onMounted(() => loadData())

    return {
      searchQuery,
      currentPage,
      pageSize,
      filteredData,
      paginatedData,
      loading,
      detailDialogVisible,
      rechargeDialogVisible,
      currentCustomer,
      rechargeForm,
      handleSearch,
      showRecharge,
      confirmRecharge
    }
  }
})
</script>

<style scoped>
.customer-page {
  padding: 20px;
}

/* 顶部搜索区 */
.top-row {
  width: 30%;
  display: flex;
  margin-bottom: 15px;
  gap: 10px;
}
.search-input {
  flex: 1;
}

/* 客户表格背景容器 */
.table-wrapper {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  overflow-x: auto; /* 保持表格横向滚动可用 */
  margin-bottom: 12px;
}

/* 分页 */
.pagination {
  text-align: right;
  margin-top: 0;
}

/* 无数据提示 */
.no-data {
  text-align: center;
  padding: 50px 0;
  color: #999;
  font-size: 14px;
}

/* 详情弹窗布局 */
.detail-content {
  display: flex;
  gap: 30px;
}
.detail-content .left {
  flex: 1;
}
.detail-content .right {
  flex: 1;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 10px;
}

/* 金额样式 */
.amount-plus {
  color: #4caf50;
  font-weight: bold;
}
.amount-minus {
  color: #f44336;
  font-weight: bold;
}

/* 余额明细固定高度，支持滚动 */
.balance-detail-table {
  max-height: 200px;
  overflow-y: auto;
  margin-top: 5px;
}

/* 充值弹窗 */
.recharge-content {
  padding: 10px 0;
}

.customer-page {
  padding: 20px;
  --row-cell-padding: 16px; /* 你想要的行高↑上下内边距越大行越高 */
}

:deep(.el-table__body-wrapper td),
:deep(.el-table__header-wrapper th) {
  padding-top: var(--row-cell-padding) !important;
  padding-bottom: var(--row-cell-padding) !important;
}
</style>
